#!/bin/bash

set -e

if [[ -n "${RASTER_VISION_DEBUG}" ]]; then
    set -x
fi

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ] ; do SOURCE="$(readlink "$SOURCE")"; done
DOCKER_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
REPO_ROOT="$( cd -P "$( dirname "$DOCKER_DIR" )" && pwd )"

function usage() {
    echo -n \
         "Usage: $(basename "$0") <options> <command>
Run a console in the Docker container locally.

Environment variables:
DATA_DIR (directory for storing data; mounted to /opt/data)
AWS_PROFILE (optional AWS profile)
RASTER_VISION_REPO (optional directory where local copy of RV is located)

Options:
--aws forwards AWS credentials (sets AWS_PROFILE env var and mounts ~/.aws to /root/.aws)
--gpu use the NVIDIA runtime and GPU image
--name sets the name of the running container
--jupyter forwards port 8888 and runs Jupyter
--debug forwards port 3000 for use with remote debugger

All arguments after above options are passed to 'docker run'.
"
}

IMAGE="{{cookiecutter.docker_image}}"

# Parse options using scheme in
# https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash
POSITIONAL=()
while [[ $# -gt 0 ]]
do
    key="$1"
    case $key in
        --help)
        usage
        exit 0
        shift
        ;;
        --aws)
        AWS="-e AWS_PROFILE=${AWS_PROFILE:-default} -v ${HOME}/.aws:/root/.aws:ro"
        shift # past argument
        ;;
        --gpu)
        IMAGE="{{cookiecutter.docker_image}}"
        RUNTIME="--runtime=nvidia"
        shift # past argument
        ;;
        --name)
        shift
        NAME="--name $1"
        shift
        ;;
        --jupyter)
        JUPYTER="-p 8888:8888"
        CMD=(jupyter notebook --ip=0.0.0.0 --no-browser --allow-root)
        shift
        ;;
        --debug)
        DEBUG="-p 3008:3000"
        shift
        ;;
        --tb)
        TB="-p 6006:6006"
        shift
        ;;
        *)    # unknown option
        POSITIONAL+=("$1") # save it in an array for later
        shift # past argument
        ;;
    esac
done
set -- "${POSITIONAL[@]}" # restore positional parameters

if [ -z "${CMD}" ]
then
    CMD=(${@:1})
fi

if [ -z "$RASTER_VISION_REPO" ]
then
    RV_SRC_FLAGS=""
else
    RV_SRC_FLAGS="-v ${RASTER_VISION_REPO}:/opt/src/"
fi

if [ "${BASH_SOURCE[0]}" = "${0}" ]
then
    docker run ${RUNTIME} ${NAME} --rm --ipc=host -it \
        -v "${HOME}"/.rastervision:/root/.rastervision \
        -v ${REPO_ROOT}/rastervision_{{cookiecutter.project_name}}:/opt/src/rastervision_{{cookiecutter.project_name}} \
        -v ${DATA_DIR}:/opt/data \
        ${RV_SRC_FLAGS} \
        ${AWS} ${JUPYTER} ${DEBUG} ${TB} \
        ${IMAGE} "${CMD[@]}"
fi
